#!/bin/sh

################################################################################
# Copyright 1999-2010 by Nice, srl.,
# Via Marchesi di Roero, 1
# 14020 Cortanze (AT) - ITALY
# All rights reserved.
#
# This software is the confidential and proprietary information
# of Nice, srl. ("Confidential Information").
# You shall not disclose such Confidential Information
# and shall use it only in accordance with the terms of
# the license agreement you entered into with Nice.
################################################################################

. "${EF_ROOT}/plugins/fm/fm/backends/common"

if [ -z "$1" ]; then
  fatal "Cannot create archive" "Missing input parameter: current path"
fi

if [ -z "$2" ]; then
  fatal "Cannot create archive" "Missing input parameter: name of the archive"
fi

if [ -z "$3" ]; then
  fatal "Cannot create archive" "Missing input parameter: format of the archive"
fi

if [ -z "$4" ]; then
  fatal "Cannot create archive" "Missing input parameter: files to archive"
fi

_fullpath="${FM_VROOT_PATH}$1"
_name="$2"
_format="$3"
_fullname="$2.$3"
_files="$4"

# Change to the required directory
cd "${_fullpath}" >/dev/null 2>&1
if [ $? -ne 0 ]; then
  fatal "Cannot create archive \"${_fullname}\"" "Cannot access to working directory"
fi

if [ -e "${_fullname}" ]; then
  error "Cannot create archive \"${_fullname}\"" "The name \"$3\" is already used in this directory. Please use a different name."
fi

do_zip () {
  _message=`echo "${_files}" | sed "s/^/'/;s/$/'/" 2>/dev/null | xargs zip -r "${_fullname}" 2>&1`
  if [ $? -ne 0 ]; then
    error "Cannot create archive \"${_fullname}\"" "${_message}"
  fi
}

do_tar () {
  _compresscmd="$1"

  # Windows specific command
  if [ "$OS" == "Windows_NT" ]; then
    _opts="H"
  else
    _opts="h"
  fi

  if [ -z "${_compresscmd}" ]; then
    echo "${_files}" | sed "s/^/'/;s/$/'/" 2>/dev/null | xargs tar cv"${_opts}"f "${_fullname}" 2>/dev/null
  else
    echo "${_files}" | sed "s/^/'/;s/$/'/" 2>/dev/null | xargs tar cv"${_opts}"f - | "${_compresscmd}" -c > "${_fullname}" 2>/dev/null
  fi

  if [ $? -ne 0 ]; then
    error "Cannot create archive \"${_fullname}\""
  fi
}

if [ -n "${_files}" ]; then
  case "${_format}" in
    zip) do_zip ;;
    tar) do_tar ;;
    tgz|tar\.gz) do_tar "gzip" ;;
    tar\.bz2) do_tar "bzip2" ;;
    tar\.Z) do_tar "compress" ;;
    *)
      fatal "Cannot create archive \"${_fullname}\"" "Invalid format ${_format}"
      ;;
  esac
fi

# ex:ts=2:et:
